<template>
    <view class="Contain"> <!-- Contain Start -->

        <view class="tabs">
            <u-tabs :list="list" :current="current" :itemStyle="itemstyles" @change="change"></u-tabs>
        </view> <!-- tabs End -->

        <view>
            <u-gap height="20" bg-color="#F7F9FD" margin-bottom="20"></u-gap>
        </view>

        <view class="orderInfo" v-if="ProductList.data[0] != undefined" v-for="(item,index) in ProductList.data" :key="item">

			<view class="orderNo">
				<view>订单: {{ item.orderno }}</view>
				<view>{{ formatTime(item.createtime)}}</view>
			</view>
	
            <view class="HomeAd">

                <u-row gutter="0">
                    <u-col span="1.5" text-align="left">
                        <view>
							<!-- -->
                            <image :src="item.shopLogo"></image>
                        </view>
                    </u-col>
                    <u-col span="7.5" text-align="left">
                        <view>{{item.shopName}}</view>
                    </u-col>
                    <u-col span="3" text-align="right">
                        <view class="link">{{ item.payStatusText }}</view>
                    </u-col>
                </u-row>

            </view> <!-- HomeAd End -->
            <view class="Photo">
                <u-row gutter="0" style="margin-bottom:20px;"  v-for="(sitem,sindex) in item.buyList">
                    <!-- /static/shop/sh1.png -->
                    <u-col span="3" text-align="center">
                        <view style="min-height:90px;" @click="$Go('../shop_order/shop_order?orderNo='+item.orderno)">
                            <image :src="sitem.imgUrl" mode="aspectFill"></image>
                        </view>
                    </u-col>
                    <u-col span="9" text-align="left">
                        <view class="PdPara">
                            <view class="black mid ptit">
                                <view class="a" @click="$Go('../shop_order/shop_order?orderNo='+item.orderNo)">
                                    <view>{{ sitem.title }}</view>
                                </view>
                                <view class="b gray">￥{{ sitem.discountVal }}</view>
                            </view>
							<block v-if="!moreProducts">
								<view class="desc" v-if="item.zhkouPrice>0">
									<view class="pa">
										积分抵扣
									</view>
									<view class="pb">
										<!-- 统一积分 -->
										<view>-{{item.diKou}}</view>
									</view>
								</view>
								<view class="desc" v-if="item.LotteryDiscount>0">
									<view class="pa">
										抽奖立减{{item.LotteryDiscount}}折
									</view>
									<view class="pb">
										<view>-￥{{item.zhkouPrice}}</view>
									</view>
								</view>
							</block>
							<block v-else>
								<view class="desc">
									<view class="pa">
										积分抵扣
									</view>
									<view class="pb">
										<!-- 展开-每个商品积分 -->
										<view>-{{sitem.jifen}}</view>
									</view>
								</view>
							</block>
                            <view class="desc">
                                <view class="pa" @click="$Go('../shop_order/shop_order?orderNo='+item.orderNo)">
                                   {{item.classifyName}}
                                </view>
                                <view class="pb">
                                    <view>x{{ sitem.buy }}</view>
                                </view>
                            </view>
                        </view>
                    </u-col>
                </u-row>
            </view> <!-- Photo End -->
            <view class="miaoshu">
                <view class="gray" @click="fuzhi(item.orderNo)">
                    <!-- 单号: <text class="gray">{{item.orderNo}}</text> --></view>
                <view>共{{ item.num }}件商品, 实付:
                    <text class="blod">￥{{ item.discountTotalPrice }}</text>
                </view>
                <!-- <view class="gray samll">{{item.createTime}}</view> -->
            </view> <!-- miaoshu End -->
			<view class="w-full flex justify-end items-center mt-2">
				<view class="w-[150rpx]"><u-button type="error" text="申请退款" size="small" @click="payBack"></u-button></view>
			</view>


            <!-- 已付款&未发货 -->
            <view class="stateBtn" v-if="item.payStatusText==='未支付'">
                <u-row gutter="0">
                    <u-col span="2" text-align="left"></u-col>
                    <u-col span="2" text-align="center"></u-col>
                    <u-col span="8" text-align="center">
                        <view class="obtn">
                            <view class="remind" @click="DelOrder(item.id,index)"
                                  style="background:#ccc;color:#FFF;border:0px;">取消订单
                            </view>
                            <view class="remind" @click="NowPay(item.orderno)" style="background:#FF3535;border:1px solid #FF3535;color:#FFF;">
                                立即支付
                            </view>
                        </view>
                    </u-col>
                </u-row>
            </view> <!-- stateBtn End -->

            <!-- 已付款&已发货 -->
            <view class="stateBtn" v-if="item.payStatusText==='已支付' && item.deliverstatue==='已发货'">
                <u-row gutter="0">
                    <u-col span="4" text-align="left"></u-col>
                    <u-col span="4" text-align="center"></u-col>
                    <u-col span="4" text-align="center">
                        <view class="remind" style="background:#017BFF !important;color:#FFFFFF !important;" @click="ComfirmOk(item.id)">确认收货</view>
                    </u-col>
                </u-row>
            </view> <!-- stateBtn End -->


            <!-- 未支付 -->
            <view class="stateBtn" v-if="item.payStatusText==='已支付' && item.deliverstatue==='未发货'">
                <u-row gutter="0">
                    <u-col span="4" text-align="left">
                        <!-- <view class="gray" @click="delOrder">删除订单</view> -->
                    </u-col>
                    <u-col span="4" text-align="center">
						<!-- <view class="contact" @click="SendMsg">提醒发货</view> -->
                    </u-col>
                    <u-col span="4" text-align="center">
						  <view class="remind" @click="$ShopServicesPhone()">联系卖家</view>
                    </u-col>
                </u-row>
            </view> <!-- stateBtn End -->

        </view> <!-- orderInfo End -->

    </view> <!-- Contain End -->
</template>

<script lang="ts" setup>
import { ref,reactive } from 'vue'
import { GoUrl, Toast } from '@/utils/utils'
import {onShow,onLoad,onHide,onReachBottom } from '@dcloudio/uni-app'
import { getAllOrdersData,deleteOrdersData,confirmOrderData } from '@/utils/apiFunction'
import { userStore } from '@/stores/userStore'
import { stdout } from 'process'
const store = userStore()

let moreProducts=ref(false);
let t:any=null;
let flag=ref(true)
let userinfo=reactive<any>(uni.getStorageSync("userinfo") ? uni.getStorageSync("userinfo") : null) 
let ProductList=reactive<any>({data:[
	{
		id:1,
		shopLogo:'',
		shopName:'',
		payStatusText:"未支付",
		orderno:"20231129205500",
		productimg:"https://img13.360buyimg.com/seckillcms/s140x140_jfs/t1/132671/24/35138/109124/64f19631F64d3905b/b8ef642f0377d564.jpg.avif",
		goodsName:"湘巧(xiangqiao)巧克力味曲奇饼干整箱早餐办公室小零食大非常好味道",
		discountPrice:99,
		JFyouhui:6, //积分优惠
		classifyName:"湘巧(xiangqiao)巧克力味曲奇饼干",
		num:68,
		discountTotalPrice:59.9,
		deliverstatue:"未发货",
		createtime:"2023-11-29"
	},
	{
		id:2,
		shopLogo:'',
		shopName:'',
		payStatusText:"已支付",
		orderno:"20231129205501",
		productimg:"https://m.360buyimg.com/seckillcms/s250x250_jfs/t1/111391/2/40557/95558/6528bf87F6f3a678e/1cb8a83cef0f6e72.jpg",
		goodsName:"朱古力好好味",
		discountPrice:99,
		JFyouhui:6,
		classifyName:"朱古力饼干",
		num:68,
		discountTotalPrice:59.9,
		deliverstatue:"未发货",
		createtime:"2023-11-29"
	},
	{
		id:3,
		shopLogo:'',
		shopName:'',
		payStatusText:"已支付",
		orderno:"20231129205501",
		productimg:"https://m.360buyimg.com/seckillcms/s250x250_jfs/t1/111391/2/40557/95558/6528bf87F6f3a678e/1cb8a83cef0f6e72.jpg",
		goodsName:"朱古力好好味",
		discountPrice:99,
		JFyouhui:6,
		classifyName:"朱古力饼干",
		num:68,
		discountTotalPrice:59.9,
		deliverstatue:"已发货",
		createtime:"2023-11-29"
	}
]}) 	
let backupProductList=reactive<any>({data:[]})  //备份当前产品信息
let offset=reactive<any>([5, 30]) 	
let itemstyles=reactive<any>({
				"width":"25%",
				"height":"45px"
})
let list=reactive<any>([
			{
				name: '全部'
			},
			{
				name: '待付款'
			}, {
				name: '待发货'
			}, {
				name: '待收货',
				count: 0
			}
])

let goodsid=ref("");
let current=ref(0)
let totalPages=ref(0)
let pages=ref(1)
let isPull=ref(false)
let orderNumber=ref('')
let orderStatus=ref(0) //获得当前登录人的订单集合:status:0-全部，1-待付款，2-待发货，3-待收货
let isLoadData=ref(false); //是否已加载过数据




let orderData=ref('');
const convertData=()=>{
	orderData.value=uni.getStorageSync("payOrderInfo") || null;
	console.log("开始转换数据...",orderData.value);
	if(orderData.value!=null){
		let index=ProductList.data.findIndex(item=>item.orderno===orderData.orderNo);
		console.log("索引:===>",index);
		if(index===-1){
			let obj={};
			obj.id=ProductList.data.length+1;
			obj.shopLogo=orderData.value.merchantInfo.imgUrl;
			obj.shopName=orderData.value.merchantInfo.title;
			obj.buyList=orderData.value.buyList;
			obj.payStatusText=orderData.value.payState;
			obj.orderno=orderData.value.orderNo;
			obj.JFyouhui=orderData.value.JfDiKou;
			obj.productimg=orderData.value.buyList[0].imgUrl;
			obj.goodsName=orderData.value.buyList[0].title;
			obj.discountPrice=orderData.value.buyList[0].discountVal;
			obj.diKou=orderData.value.diKou;
			obj.classifyName="数量";
			obj.num=orderData.value.buyList.length;
			obj.discountTotalPrice=orderData.value.realPay;
			obj.deliverstatue=orderData.value.deliveryState;
			obj.LotteryDiscount=orderData.value.LotteryDiscount;
			obj.zhkouPrice=orderData.value.zhkouPrice;
			obj.createtime=orderData.value.time;
			ProductList.data.push(obj);
			console.log("ProductList.data===>",ProductList.data);
			uni.setStorageSync("orderProductList",ProductList.data);
		}
	}
}

//加油数据转换，并接追加到 orderProductList 对象里
const convertJiYouData=()=>{
	let jiayouOrder=uni.getStorageSync("jiayouPayInfo") || null;
	if(jiayouOrder!=null){
		let index=ProductList.data.findIndex(item=>item.orderno===jiayouOrder.orderNo);
		if(index===-1){
			let obj={};
			obj.id=ProductList.data.length+1;
			obj.shopLogo=jiayouOrder.JYsiteInfo.imgUrl;
			obj.shopName=jiayouOrder.JYsiteInfo.title;
			
			obj.buyList=[];
			let temp={};
			temp.imgUrl=jiayouOrder.JYsiteInfo.imgUrl;
			temp.buy=jiayouOrder.buyNumber;
			temp.discountVal=jiayouOrder.originPrice;
			temp.jifen=jiayouOrder.diKouJF;
			temp.title=jiayouOrder.gunInfo;
			obj.buyList.push(temp);
			
			obj.payStatusText="已付款";
			obj.orderno=jiayouOrder.orderNo;
			obj.JFyouhui=jiayouOrder.diKouJF;
			obj.productimg=jiayouOrder.JYsiteInfo.imgUrl;
			obj.goodsName=jiayouOrder.gunInfo;
			obj.discountPrice=jiayouOrder.realPay;
			obj.classifyName="加油";
			obj.num=1;
			obj.discountTotalPrice=jiayouOrder.realPay;
			obj.deliverstatue="未发货";
			obj.createtime=jiayouOrder.time;
			ProductList.data.push(obj);
			console.log("ProductList.data===>",ProductList.data);
			uni.setStorageSync("orderProductList",ProductList.data);
		}
	}
}

const payBack=()=>{
	uni.showModal({
		title:"温馨提示",
		content:"是否申请退款",
		showCancel:true,
		success:res=>{
			if(res.confirm){
				ProductList.data=[];
				uni.removeStorageSync("orderProductList");
			}
		}
	})
}

onLoad((opts:any)=>{
	if (opts.statenum != null) {
		current.value = opts.statenum;
		orderStatus.value = opts.statenum;
		uni.setStorageSync("statenum",orderStatus.value);
		isLoadData.value=true;
		//QueryAllOrder(true);
	}else{
		orderStatus.value=uni.getStorageSync("statenum");
		if(orderStatus.value!=null){
			isLoadData.value=true;
			//QueryAllOrder(true);
		}
	}	
})

onHide(()=>{
	flag.value = false
})


onShow(()=>{
	
	ProductList.data=[];
	
	convertData(); //美食转换数据格式
	convertJiYouData(); //加油站格式转换
	/*
	let Temp=uni.getStorageSync("orderProductList") || null;
	if(Temp===null || ProductList.data[0]===undefined){
		ProductList.data=[];
		convertData(); //转换数据格式
	}else{
		ProductList.data=uni.getStorageSync("orderProductList");
	}
	//*/
	
	flag.value = true
	pages.value = 1;
	isPull.value = false;
	
	backupProductList.data=ProductList.data;
	/* ProductList.data = []
	//查询所有订单
	if(isLoadData.value==false){
		if(store.userData.userinfo.id!=null){
			Toast("正在获取订单..")
			QueryAllOrder(false);
		}		
	} */
	
	
	
})





const countPro=(obj:any)=>{
	if (typeof obj === 'object') return obj.length;
	return 0;
}

const formatTime=(dateval:string)=>{
	if(dateval===null) return null;
	if(dateval==='') return '';
	dateval=dateval.replace("T"," ");
	if(dateval.indexOf(" ")!=-1){
		return dateval.split(" ")[0];
	}
	return dateval;
}



//确认收货
const ComfirmOk=(orderId:string)=>{
	uni.showModal({
		title: '操作提示',
		content: '是否确认已收到商品！',
		showCancel: true,
		success:async ok => {
			if(ok.confirm){
				let paraData={
					id:orderId,
					deliverstatue:"交易完成",
				}
				let res:any = await confirmOrderData(paraData); // Api
				//console.log("获取所有订单数据:",res);
				if(res.data.code===200){
					Toast("交易完成")
				}else{
					Toast("状态更新失败")
				}				
			}

		},
		fail: err => {
			
		},
	});
}


//赋值订单号
const fuzhi=(orderNo:string)=>{
	uni.setClipboardData({
		data: orderNo,
		success: () => {
			console.log('success');
			Toast(orderNo + " 单号已复制");
		}
	});
}


const change=(e:any)=>{
	console.log("切换:", e);
	pages.value = 1;
	isPull.value = false;
	current.value = e.index;  //status:0-全部，1-未支付，2-待发货，3-待收货
	//orderStatus.value = e.index;
	ProductList.data=backupProductList.data;
	
	console.log("过滤产品信息")
	if(e.name==="全部"){
		ProductList.data=backupProductList.data;
	}
	if(e.name==="待付款"){
		ProductList.data=ProductList.data.filter(item=>item.payStatusText==='未支付');
	}
	if(e.name==="待发货"){
		ProductList.data=ProductList.data.filter(item=>item.payStatusText==='已支付' && item.deliverstatue==='未发货');
	}
	if(e.name==="待收货"){
		ProductList.data=ProductList.data.filter(item=>item.payStatusText==='已支付' && item.deliverstatue==='已发货');
	}
	console.log("ProductList.data:",ProductList.data);
}


//查询当前用户所有订单信息
const QueryAllOrder=async (isFilter:boolean)=>{
	let paraData={
		userid:store.userData.userinfo.id
	};
	let res:any = await getAllOrdersData(paraData); // Api
	console.log("获取所有订单数据:",res);
	if(res.data.code===200){
		isLoadData.value=true;
		uni.hideLoading();
		ProductList.data=[];
		if(res.data.AlllistOrders.length>0){
			res.data.AlllistOrders.forEach(item=>{
				var obj:any={};
				obj.id=item.id;
				obj.payStatusText=item.paystatue;	
				obj.orderno=item.orderno;
				obj.productimg=item.productimg;
				obj.goodsName=item.productname;
				obj.discountPrice=item.orderprice;
				obj.classifyName=item.productname;
				obj.num=item.buynumber;
				obj.discountTotalPrice=item.totalpay;
				obj.deliverstatue=item.deliverstatue;
				obj.createtime=item.createtime;
				ProductList.data.push(obj);
			})
			backupProductList.data=ProductList.data;
			console.log("产品ProductList",ProductList,isFilter);
			if(isFilter){
				let objData:any={};
				//console.log("orderStatus.value==>",parseInt(orderStatus.value.toString()),typeof orderStatus.value);
				switch(parseInt(orderStatus.value.toString())){
					case 0:
						objData.count=0;
						objData.index=0;
						objData.name="全部";
						break;
					case 1:
						objData.count=0;
						objData.index=1;
						objData.name="待付款";
						break;
					case 2:
						objData.count=0;
						objData.index=2;
						objData.name="待发货";
						break;
					case 3:
						objData.count=0;
						objData.index=3;
						objData.name="待收货";	
						break;
					break;
				}
				console.log("objData:===>",objData);
				change(objData);	
			}
		}
	}else{
		uni.hideLoading();
	} 
}


 //删除订单
const DelOrder=(orderId:string,index:number)=>{
	/* console.log("orderId",orderId);
	ProductList.data.splice(index,1);
	return; */
	uni.showModal({
		title: '系统提示',
		content: '是否删除该订单',
		success:async (res)=>{
			if (res.confirm) {
				let paraData={
					id:orderId
				};
				let res:any = await deleteOrdersData(paraData);
				console.log("删除订单数据",index,res);
				if(res.data.code===200){
					uni.hideLoading();
					ProductList.data.splice(index,1);
					Toast("订单已删除")
				}else{
					uni.hideLoading();
				}
				
			} else if (res.cancel) {
				console.log('用户点击取消');
			}
		}
	})
}


//去支付,把当前订单号放入购物车再跳转至订单页面
const NowPay=(OrderNo:string)=>{
	console.log("OrderNo:",OrderNo);
	GoUrl("../shop_order/shop_order?orderNo="+OrderNo);
}

const SendMsg=()=>{
    Toast("已提醒卖家发货");
}


const confirm=()=>{
	//取消订单
	let PayPara = {
		"orderNo": orderNumber,
	}
	console.log("删除订单参数:", PayPara);
}



onReachBottom(()=>{
	//分页加载
	/* if (pages > totalPages) {
		isPull.value = false;
		Toast("没数据啦,我也是有底线的~");
		return;
	}
	isPull.value = true;
	pages.value +=1;
	QueryAllOrder(false);	 */
})


</script>

<style scoped lang="scss">
@import "shop_allorder.scss";
</style>